use serde::{Deserialize, Serialize};

#[derive(Debug)]
pub enum IdField {
    Text(String),
    Number(i64),
}

impl Default for IdField {
    fn default() -> Self {
        IdField::Text(String::new())
    }
}

impl IdField {
    pub fn as_string(&self) -> String {
        match self {
            IdField::Text(s) => s.clone(),
            IdField::Number(n) => n.to_string(),
        }
    }

    pub fn as_i64(&self) -> i64 {
        match self {
            IdField::Text(s) => s.parse::<i64>().unwrap_or(0),
            IdField::Number(n) => *n,
        }
    }
}

impl Serialize for IdField {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            IdField::Text(s) => serializer.serialize_str(s),
            IdField::Number(n) => serializer.serialize_i64(*n),
        }
    }
}

impl<'de> Deserialize<'de> for IdField {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct IdFieldVisitor;

        impl<'de> serde::de::Visitor<'de> for IdFieldVisitor {
            type Value = IdField;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a string or a number")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(IdField::Text(value.to_owned()))
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(IdField::Text(value))
            }

            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(IdField::Number(value))
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(IdField::Number(value as i64))
            }
        }

        deserializer.deserialize_any(IdFieldVisitor)
    }
}
